package com.example.administrator.xmut.kcb;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.administrator.xmut.MainActivity;
import com.example.administrator.xmut.http.CourseBean;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class GetTimeTable  extends AppCompatActivity {

    int course_nameId=0,course_weekId=0,course_teacherId=0,course_addressId=0;
    public static String responseCookie;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        final List<CourseBean> course = new ArrayList<CourseBean>();
        super.onCreate(savedInstanceState);
        new Thread(LoginJWXT).start();

    }

    public void getkcb() throws Exception {
        SharedPreferences sharedPreferences = getSharedPreferences("test",
                MainActivity.MODE_PRIVATE);
        String html =sharedPreferences.getString("jwxturl", "");
        BufferedReader reader = null;
        HttpURLConnection ConnectionGetcookie = null;
        HttpURLConnection connectionJWXTHost = null;
        HttpURLConnection connectionKCB = null;
        try {
            // 新建一个URL对象，指定到请求的url.
            URL urlJWXTHOST = new URL(html);
            URL urlKCB = new URL("http://210.34.213.67/xskbcx.aspx?xh=1407012215&xm=%C1%D6%C0%A4%BA%A3&gnmkdm=N121603");
            ConnectionGetcookie = (HttpURLConnection) urlJWXTHOST.openConnection();
            responseCookie = ConnectionGetcookie.getHeaderField("Set-Cookie");
            //得到教务系统HOST Cookie
            Log.e("dddd", "得到教务系统HOSTCookie=    " + responseCookie);
            connectionJWXTHost = (HttpURLConnection) urlJWXTHOST.openConnection();
            connectionJWXTHost.setRequestProperty("Cookie", responseCookie);
            new InputStreamReader(connectionJWXTHost
                    .getInputStream(), "gb2312");
            //进入一次教务系统主页才能得到课程表和成绩


            connectionKCB = (HttpURLConnection) urlKCB.openConnection();
            connectionKCB.setRequestProperty("Cookie", responseCookie);
            connectionKCB.setRequestProperty("Referer", "http://210.34.213.67/xs_main.aspx?xh=1407012215");
            connectionKCB.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
            reader = new BufferedReader(new InputStreamReader(connectionKCB
                    .getInputStream(), "gb2312"));
            String line = null;
            String html1 = null;
            while ((line = reader.readLine()) != null) {
                html1 += line;
            }

            Document doc = Jsoup.parse(html1);
            List<CourseBean> resolveKB = resolveKB(doc.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            ConnectionGetcookie.disconnect();
        }

    }


    private List<CourseBean> resolveKB(String html) {
        SharedPreferences mySharedPreferences= getSharedPreferences("test",
                MainActivity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();

        Pattern pattern1 = Pattern.compile("width=\"7%\">.*?/td>");
        Matcher matcher1 = pattern1.matcher(html);
        StringBuffer sb = new StringBuffer();
        int begin = 0;
        int end = 0;
        while (matcher1.find()) {
            begin = matcher1.start();
            end = matcher1.end();
            String str = html.substring(begin + 11, end);
            sb.append(str);
        }

        pattern1 = Pattern.compile("rowspan=\"2\">.*?/td>");
        matcher1 = pattern1.matcher(html);

        while (matcher1.find()) {
            begin = matcher1.start();
            end = matcher1.end();
            String str = html.substring(begin + 12, end);
            sb.append(str);
        }

        String str = sb.toString().replaceAll("<font.*?</font>", "");
        String[] str1 = str.split("</td>");

        ArrayList<CourseBean> course = new ArrayList<CourseBean>();
        for (String s : str1) {
            String[] k = s.split("<br />");
            for (int i = 0; i < k.length && k.length > 1; ) {

                String course_name = k[i++];
                Log.e("dddd", course_name+course_nameId);
                editor.putString("course_name__" + course_nameId++, course_name);

                String course_week = k[i++];
                Log.e("dddd", course_week + course_weekId);
                editor.putString("course_week__" + course_weekId++, course_week);

                String course_teacher = k[i++];
                editor.putString("course_teacher__" + course_teacherId++, course_teacher);

                String course_address = k[i++];
                editor.putString("course_address__" + course_addressId++, course_address);

                CourseBean c = new CourseBean(course_name, course_address,
                        course_teacher, course_week);
                course.add(c);
                editor.commit();
            }
        }
        editor.putInt("Size", course_nameId);
        editor.putBoolean("isLogin", true);
        editor.commit();
        ArrayList<CourseBean> timeTable = course;
        return course;
    }

    Runnable LoginJWXT = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                getkcb();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };


}


